package com.wang.cloud.manage.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.cloud.manage.domain.entity.UserRoleRelationEntity;
import com.wang.cloud.manage.domain.vo.RoleNameVo;
import com.wang.cloud.manage.domain.vo.UserRoleNameVo;
import com.wang.cloud.manage.mapper.UserRoleRelationMapper;
import com.wang.cloud.manage.service.IUserRoleRelationService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统用户和角色关联表 服务实现类
 * </p>
 *
 * @author wy
 * @since 2024-07-16
 */
@Service
public class UserRoleRelationServiceImpl extends ServiceImpl<UserRoleRelationMapper, UserRoleRelationEntity> implements IUserRoleRelationService {


    @Override
    public Boolean delByUser(Long userId) {
        return this.lambdaUpdate()
                .eq(UserRoleRelationEntity::getUserId, userId)
                .remove();
    }

    @Override
    public Boolean saveUserRoles(Long userId, Collection<Long> rolesIds) {
        if (ObjectUtil.isEmpty(rolesIds)) {
            return Boolean.FALSE;
        }
        List<UserRoleRelationEntity> list = rolesIds.stream()
                .distinct()
                .filter(Objects::nonNull)
                .map(roleId -> {
                    UserRoleRelationEntity relation = new UserRoleRelationEntity();
                    relation.setUserId(userId);
                    relation.setRoleId(roleId);
                    return relation;
                })
                .collect(Collectors.toList());
        if (list.isEmpty()) {
            return Boolean.TRUE;
        }
        return this.saveBatch(list, 200);
    }

    @Override
    public List<Long> queryRoleIdsByUserId(Long userId) {
        return baseMapper.queryRoleIdsByUserId(userId);
    }

    @Override
    public List<RoleNameVo> queryRoleNamesByUserId(Long userId) {
        return baseMapper.queryRoleNamesByUserId(userId);
    }

    @Override
    public Map<Long, List<UserRoleNameVo>> queryRoleByUserIds(Collection<Long> userIds) {
        if (ObjectUtil.isEmpty(userIds)) {
            return Collections.emptyMap();
        }
        List<UserRoleNameVo> list = baseMapper.queryRoleByUserIds(userIds);
        Map<Long, List<UserRoleNameVo>> map = list.stream()
                .collect(Collectors.groupingBy(UserRoleNameVo::getUserId));
        return map;
    }
}
